package ThreadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DemoExecutorService {

	private static Callable<String> task1 = new Callable<String>() {

		@Override
		public String call() throws Exception {
			Thread.sleep(2 * 1000);
			System.out.println(Thread.currentThread().getName());
			return "task1";
		}
	};

	private static Callable<String> task2 = new Callable<String>() {

		@Override
		public String call() throws Exception {
			Thread.sleep(5 * 1000);
			return "task2";
		}
	};

	public static void main(String[] args) {
		List<Future<String>> list = new ArrayList<Future<String>>();

		ExecutorService exec = Executors.newFixedThreadPool(2);

		Future<String> future1 = exec.submit(task1); // execute方法返回void，更多的使用submit方法返回future
		Future<String> future2 = exec.submit(task2);
		list.add(future1);
		list.add(future2);

		try {
			for (Future<String> future : list)
				System.out.println(future.get()); // 阻塞在get方法这里
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			future2.cancel(true);
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("=====");
		// exec.shutdown();
		exec.shutdownNow();
	}
}
